import React, { useState } from 'react'

function UseHooks() {
    const [s1, setS1] = useState(() => 0)
    const [s2, setS2] = useState(0)

    function onclick () {
        // 相同的函数会依次执行，然后再合并render
        setS1(s1=>s1+1)
        console.log("s1:", s1)

        setS1(s1=>s1+1)
        console.log("s1:", s1)

        // 相同的对象数据会覆盖前一个对象，然后再合并render
        setS2(s2+1)
        console.log("s2:", s2)

        setS2(s2+1)
        console.log("s2:", s2)
    }

    return (
        <div>
            <div>{s1}</div>
            <div>{s2}</div>
            <button onClick={onclick}>按钮</button>
        </div>
    )
}


class HookComponent extends React.Component{
    constructor () {
        super()
        this.state = {
            s1: 0,
            s2: 0
        }

        this.onclick = this.onclick.bind(this)
    }
    onclick () {
        this.setState({s1: this.state.s1 + 1})
        console.log("s1:", this.state.s1)
        this.setState({s1: this.state.s1 + 1})
        console.log("s1:", this.state.s1)

        this.setState(preState => ({s2: preState.s2 + 1}))
        console.log("s2:", this.state.s2)
        this.setState(preState => ({s2: preState.s2 + 1}))
        console.log("s2:", this.state.s2)
    }
    render () {
        return (
            <div>
                <div>{this.state.s1}</div>
                <div>{this.state.s2}</div>
                <button onClick={this.onclick}>按钮</button>
            </div>
        )
    }
}

export default HookComponent
